/* eslint-disable react/require-default-props */
import React, { useEffect, useState } from 'react';

import { Col, Empty, message, Row, Spin, Tabs, Tooltip } from 'antd';
import PropTypes from 'prop-types';
import { history } from 'umi';

import { GuideByServerFlag } from '@/components';
import { useRequest } from '@/hooks';
import { findCodeFn } from '@/pages/Notice/HomePage/utils';
import { getCommonEntrance } from '@/services/notice/homePage';
import { eventTrack } from '@/utils/track';

import { FlowIcon } from '../../../../WorkFlow/components/BasicSettingForm/components';
import homepageStyles from '../../homepage.less';
import { SettingBar } from '../common/TabBarExtraContent';
import QuickCheckModal from './QuickCheckModal';
import styles from './index.less';

const { TabPane } = Tabs;
/**
 * 常用流程
 */
const Cylc = props => {
    const { responders } = props;
    const { onDelete, onAdd, droppableProps } = responders;
    const [visible, setVisible] = useState(false);

    const [selectedData, setSelectedData] = useState([]);
    const [unselectedData, setUnselectedData] = useState([]);

    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const { employeeCode } = user;

    // TODO 通过css 自动排列
    // 通过所在列计算
    const positionSide = droppableProps['data-rbd-droppable-id'] === 'droppable' ? 'left' : 'right';
    const grid = positionSide === 'left' ? 4 : 6;
    const titleStyle = {
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        width: '100%'
    };

    // 跳转至流程
    const linkToDetail = subItem => {
        // 流程
        if (subItem.itemType === 'flow') {
            history.push({
                pathname: '/personal/portal/apply',
                query: {
                    id: subItem.itemId,
                    employeeCode,
                    name: subItem.itemName
                }
            });
        } else if (subItem.itemType === 'shortcuts') {
            const { path = '' } = findCodeFn(subItem.itemId);
            history.push({
                pathname: path,
                query: {}
            });
        }
    };

    const { run: fetchCommonEntrance, loading } = useRequest(getCommonEntrance, {
        manual: true,
        onSuccess: result => {
            const { code, data, msg } = result;
            if (code === 10000) {
                setSelectedData(data?.checkList || []);
                setUnselectedData(data?.groupList || []);
            } else {
                message.error(msg);
            }
        }
    });

    const onOk = () => {
        setVisible(false);
        fetchCommonEntrance();
    };

    useEffect(() => {
        // TODO 拖拽时到不同列时子组件会重载
        fetchCommonEntrance();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
        <Spin spinning={loading}>
            <Tabs
                defaultActiveKey="1"
                className={`${homepageStyles.wnWdlcTitle} ${styles.noTabActiveLine}`}
                tabBarExtraContent={
                    <SettingBar
                        onDelete={onDelete}
                        onAdd={onAdd}
                        setVisible={setVisible}
                        onClick={() => {
                            eventTrack({
                                eventName: 'portal_common_flow_set_click',
                                pageName: 'personal_portal'
                            });
                        }}
                    />
                }
            >
                <TabPane
                    className={styles.tabContent}
                    tab={
                        <GuideByServerFlag.Step
                            index={1}
                            content={
                                <span className={styles.cylc_step}>
                                    <strong>“常用流程”</strong>和<strong>“快捷功能”</strong>合并到这里了
                                </span>
                            }
                            placeholderStyle={{ display: 'block' }}
                            placement="topLeft"
                        >
                            <span>常用入口</span>
                        </GuideByServerFlag.Step>
                    }
                    key="1"
                >
                    <div className={styles.cylcWrapper}>
                        <Row gutter={10}>
                            {selectedData.length === 0 ? (
                                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            ) : (
                                selectedData.map((item, index) => (
                                    <Col
                                        // eslint-disable-next-line react/no-array-index-key
                                        key={`${item.itemId}-${index}`}
                                        span={grid}
                                        style={{
                                            textAlign: 'center',
                                            overflow: 'hidden',
                                            marginBottom: 8
                                        }}
                                    >
                                        <div
                                            className={styles.flex_dire_nowrap}
                                            onClick={() => {
                                                // 埋点
                                                eventTrack({
                                                    eventName: 'portal_common_flow_click',
                                                    pageName: 'personal_portal',
                                                    eventProps: {
                                                        click_context: item.itemName
                                                    }
                                                });
                                                linkToDetail(item);
                                            }}
                                        >
                                            <FlowIcon value={item.iconType} />
                                            <Tooltip title={item.itemName} placement="bottom">
                                                <div style={titleStyle}>{item.itemName}</div>
                                            </Tooltip>
                                        </div>
                                    </Col>
                                ))
                            )}
                        </Row>
                    </div>
                    {visible && (
                        <QuickCheckModal
                            visible={visible}
                            selectedModule={selectedData}
                            unselectedModule={unselectedData}
                            onOk={onOk}
                            onCancel={() => setVisible(false)}
                        />
                    )}
                </TabPane>
            </Tabs>
        </Spin>
    );
};
Cylc.propTypes = {
    config: PropTypes.shape({
        // 是否可以拖动
        isDragDisabled: PropTypes.bool
    }),
    responders: PropTypes.shape({
        onBeforeCapture: PropTypes.bool
        // ...
    })
};
export default React.memo(Cylc);
